package com.dgshanger.sanhxiaofeisc.ui.home.activity

import android.content.Intent
import android.text.TextUtils
import android.view.View
import android.webkit.WebSettings
import android.widget.LinearLayout
import com.dgshanger.sanhxiaofeisc.R
import com.dgshanger.sanhxiaofeisc.mvp.contract.EnterProtocolContract
import com.dgshanger.sanhxiaofeisc.mvp.presenter.EnterProtocolPresenter
import com.dgshanger.sanhxiaofeisc.ui.home.utils.CommonUtils
import com.xx.baseuilibrary.mvp.lcec.BaseMvpLcecActivity
import kotlinx.android.synthetic.main.activity_enter_protocol.*
import org.jsoup.Jsoup

/**
 * Created by JacobHHH on 2018/4/22.
 * 入驻协议
 */
class EnterProtocolActivity : BaseMvpLcecActivity<LinearLayout,String,EnterProtocolContract.Model,EnterProtocolContract.View,EnterProtocolPresenter>() ,EnterProtocolContract.View, View.OnClickListener {

    override fun createPresenter(): EnterProtocolPresenter = EnterProtocolPresenter()

    override fun getActivityLayoutId(): Int = R.layout.activity_enter_protocol

    override fun initData() {
        super.initData()
        initView()
        loadData(true)

    }

    private fun initView() {
        tv_consent.setOnClickListener(this)
    }

    override fun loadData(refresh: Boolean) {
        presenter.loadData()
    }

    override fun initEvent() {

    }

    override fun onClick(view: View?) {
        when(view!!.id){
            R.id.tv_consent->{
                val intent = Intent(mContext, ShopEnterActivity::class.java)
                startActivity(intent)
            }
        }
    }

    override fun setData(body: String?) {
        showContent()
        initWebView(body!!)
    }

    private fun initWebView(body : String)  {
        if (!TextUtils.isEmpty(body)) {
            if (CommonUtils.isNetWorkConnected(mContext)) {
                //根据cache-control决定是否从网络上取数据。
                webView.settings.cacheMode = WebSettings.LOAD_DEFAULT
            } else {
                webView.settings.cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK//没网，则从本地获取，即离线加载
            }
            webView.settings.loadWithOverviewMode = true// 缩放至屏幕的大小
            webView.loadDataWithBaseURL(null, getNewContent(body), "text/html", "utf-8", null)
        }
    }


    private fun getNewContent(htmlText: String): String {
        val doc = Jsoup.parse(htmlText)
        val elements = doc.getElementsByTag("img")
        for (element in elements) {
            element.attr("width", "100%").attr("height", "auto")
        }
        return doc.toString()
    }

}